import { useTokenStore } from '../stores/token.js'
import request from '../utils/request.js'

//任务列表
export const taskService = (params) => {
    const tokenStore = useTokenStore();
    return request.get('/task/list', { 
        headers: { 'Authorization': tokenStore.token },
        params: params
    });
}

// 修改删除任务的接口
export const deletetask = async (id) => {
    const tokenStore = useTokenStore();
    try {
        // 直接在 URL 中传递 id 参数
        const response = await request.delete(`/task/delete?id=${id}`, {
            headers: {
                'Authorization': tokenStore.token,
                'Content-Type': 'application/json'
            }
        });
        return response;
    } catch (error) {
        console.error('删除任务失败:', error);
        throw error;
    }
}

// 修改更新任务的接口
export const updateTask = (taskData) => {
    const tokenStore = useTokenStore();
    return request.post('/task/update', 
        taskData,
        {
            headers: { 
                'Authorization': tokenStore.token,
                'Content-Type': 'application/json'
            }
        }
    ).then(response => {
        // 直接返回响应数据
        return response;
    }).catch(error => {
        console.error('更新任务失败:', error);
        throw error;
    });
}

// 获取当前用户的任务
export const getUserTasks = () => {
    const tokenStore = useTokenStore();
    return request.get('/task/allmytasks', {
        headers: { 'Authorization': tokenStore.token }
    });
}


// 接单
export const acceptTask = (taskId) => {
    const tokenStore = useTokenStore();
    return request({
        url: '/task/order',
        method: 'post',
        headers: { 
            'Authorization': tokenStore.token,
            'Content-Type': 'application/json'
        },
        data: {
            taskId: taskId
        }
    }).then(response => {
        return response;
    }).catch(error => {
        console.error('接单失败:', error);
        throw error;
    });
}


// 获取用户接单任务列表
export const getUserOrderTasks = (params) => {
    const tokenStore = useTokenStore();
    return request({
        url: '/task/orders',
        method: 'get',
        headers: { 
            'Authorization': tokenStore.token,
            'Content-Type': 'application/json'
        },
        params: params
    }).then(response => {
        console.log('获取我的接单任务响应:', response);
        return response;
    }).catch(error => {
        console.error('获取我的接单任务失败:', error);
        throw error;
    });
}

// 通过taskId更新订单状态
export const updateTaskOrderStatus = (taskId, status) => {
    const tokenStore = useTokenStore();
    console.log('Sending request with:', { taskId, status }); // 添加日志
    return request({
        url: '/task/status',
        method: 'post',
        headers: { 'Authorization': tokenStore.token },
        data: {
            taskId: taskId,
            status: status
        }
    });
}


